package com.gzdh.tang.modu.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeQueryModel;
import com.alipay.api.domain.AlipayTradeRefundModel;
import com.alipay.api.request.AlipayDataDataserviceBillDownloadurlQueryRequest;
import com.alipay.api.request.AlipayTradePayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayDataDataserviceBillDownloadurlQueryResponse;
import com.alipay.api.response.AlipayTradePayResponse;

import com.alipay.api.response.AlipayTradeQueryResponse;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gzdh.tang.comm.handler.IPayRuleHandler;
import com.gzdh.tang.comm.util.ObjectUtil;
import com.gzdh.tang.comm.util.SnowFlake;
import com.gzdh.tang.comm.vo.Result;
import com.gzdh.tang.config.ali.AliPayUtil;
import com.gzdh.tang.config.weixin.WXEntity;
import com.gzdh.tang.config.weixin.WXPay;
import com.gzdh.tang.config.weixin.WXPayUtils;
import com.gzdh.tang.modu.dto.InventoryNumberDto;
import com.gzdh.tang.modu.entity.*;
import com.gzdh.tang.modu.model.CarFoodsModel;
import com.gzdh.tang.modu.model.DeviceCarModel;
import com.gzdh.tang.modu.model.dk.JsonsRootBean;
import com.gzdh.tang.modu.service.*;
import com.gzdh.tang.modu.vo.InStockTempVo;
import com.gzdh.tang.modu.vo.PayResVo;
import com.gzdh.tang.warehouse.entity.Device;
import com.gzdh.tang.warehouse.service.DeviceService;
import com.gzdh.tang.warehouse.service.InStockService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@Slf4j
@RequestMapping(value = "/tang/order")
public class PayController {

    @Autowired
    TangOrderService tangOrderService;

    @Autowired
    TangOrderDetailsService tangOrderDetailsService;

    @Autowired
    TangAddrService addrService;

    @Autowired
    InStockService inStockService;

    @Autowired
    DeviceService deviceService;


    @Autowired
    TangDeviceService tangDeviceService;

    @Autowired
    FkService fkService;
    @Autowired
    GsService gsService;


    @Autowired
    ReserveService reserveService;

    /**
     * @param deviceCarModel
     * @return
     */
    @PostMapping("toPrePay")
    public Result<Object> toPrePay(@RequestBody DeviceCarModel deviceCarModel) {
        Result<Object> result = new Result<>();
        String date = new SimpleDateFormat("MMdd").format(new Date());
        sumJe(deviceCarModel);//计算价格
        Map<String, String> resMap = new HashMap<>();
        String orders = "WXZF" + date + SnowFlake.nextId();
        resMap.put("orders", orders);
        resMap.put("amountPrice", deviceCarModel.getAmountPrice().stripTrailingZeros().toPlainString());
        TangOrder tangOrder = new TangOrder();
        tangOrder.setOrders(orders);
        tangOrder.setOperaId(deviceCarModel.getOperaId());
        tangOrder.setPosNum(deviceCarModel.getPosNum());
        tangOrder.setPayChannel(0);
        tangOrder.setPayState(0);
        tangOrder.setNoticeReserve(0);
        tangOrder.setAddr(deviceCarModel.getAddr());
        tangOrder.setAmountCount(deviceCarModel.getAmountCount().intValue());
        tangOrder.setAmountPrice(deviceCarModel.getAmountPrice().stripTrailingZeros().toPlainString());
        tangOrder.setQcCode(tangOrderService.getLiuShui());
        tangOrder.setCreateTime(new Date());
        tangOrderService.save(tangOrder);
        List<TangOrderDetails> tangOrderDetailsList = new ArrayList<>();
        for (CarFoodsModel goo : deviceCarModel.getCarFoods()) {
            TangOrderDetails tangOrderDetails = new TangOrderDetails();
            tangOrderDetails.setOrdersId(tangOrder.getId());
            tangOrderDetails.setBmzl(goo.getZl());
            tangOrderDetails.setNumber(goo.getFoodNumber());
            tangOrderDetails.setCode(goo.getBm());
            tangOrderDetails.setFoodName(goo.getName());
            tangOrderDetails.setPrice(goo.getPrice());
            tangOrderDetails.setAmountPrice(new BigDecimal(goo.getPrice()).multiply(new BigDecimal(goo.getFoodNumber())).toPlainString());
            tangOrderDetailsList.add(tangOrderDetails);
        }
        tangOrderDetailsService.saveBatch(tangOrderDetailsList);
        result.setResult(resMap);
        return result;
    }


    @PostMapping("preFacePay")
    public Result<Object> preFacePay(@RequestBody List<DeviceCarModel> deviceCarModelList) {
        BigDecimal amountPrice = new BigDecimal(0);
        String date = new SimpleDateFormat("MMdd").format(new Date());
        Map<String, String> resMap = new HashMap<>();
        String orders = "FACE" + date + SnowFlake.nextId();
        resMap.put("orders", orders);
        for (DeviceCarModel goo : deviceCarModelList) {
            preBatch(goo, orders);
            amountPrice = amountPrice.add(goo.getAmountPrice());
        }
        resMap.put("amountPrice", amountPrice.stripTrailingZeros().toPlainString());
        Result<Object> result = new Result<>();
        result.setResult(resMap);
        return result;
    }

    @PostMapping("toPrePayBatch")
    public Result<Object> toPrePayBatch(@RequestBody List<DeviceCarModel> deviceCarModelList) {
        Result<Object> result = new Result<>();
        BigDecimal amountPrice = new BigDecimal(0);
        String date = new SimpleDateFormat("MMdd").format(new Date());
        Map<String, String> resMap = new HashMap<>();
        String orders = "WXZF" + date + SnowFlake.nextId();
        resMap.put("orders", orders);
//        resMap.put("amountPrice", deviceCarModel.getAmountPrice().stripTrailingZeros().toPlainString());
        for (DeviceCarModel goo : deviceCarModelList) {
            preBatch(goo, orders);
            amountPrice = amountPrice.add(goo.getAmountPrice());
        }
        resMap.put("amountPrice", amountPrice.stripTrailingZeros().toPlainString());
        result.setResult(resMap);
        return result;
    }

    private void preBatch(DeviceCarModel deviceCarModel, String orders) {
        String liushui = tangOrderService.getLiuShui();
        sumJe(deviceCarModel);//计算价格
        TangOrder tangOrder = new TangOrder();
        tangOrder.setOrders(orders);
        tangOrder.setOperaId(deviceCarModel.getOperaId());
        tangOrder.setPosNum(deviceCarModel.getPosNum());
        tangOrder.setPayChannel(0);
        tangOrder.setPayState(0);
        tangOrder.setNoticeReserve(0);
        tangOrder.setAddr(deviceCarModel.getAddr());
        tangOrder.setAmountCount(deviceCarModel.getAmountCount().intValue());
        tangOrder.setAmountPrice(deviceCarModel.getAmountPrice().stripTrailingZeros().toPlainString());
        tangOrder.setQcCode(liushui);
        tangOrder.setCreateTime(new Date());
        tangOrderService.save(tangOrder);
        List<TangOrderDetails> tangOrderDetailsList = new ArrayList<>();
        for (CarFoodsModel goo : deviceCarModel.getCarFoods()) {
            TangOrderDetails tangOrderDetails = new TangOrderDetails();
            tangOrderDetails.setOrdersId(tangOrder.getId());
            tangOrderDetails.setBmzl(goo.getZl());
            tangOrderDetails.setNumber(goo.getFoodNumber());
            tangOrderDetails.setCode(goo.getBm());
            tangOrderDetails.setFoodName(goo.getName());
            tangOrderDetails.setPrice(goo.getPrice());
            tangOrderDetails.setAmountPrice(new BigDecimal(goo.getPrice()).multiply(new BigDecimal(goo.getFoodNumber())).toPlainString());
            tangOrderDetailsList.add(tangOrderDetails);
        }
        tangOrderDetailsService.saveBatch(tangOrderDetailsList);
    }


    @GetMapping("microPay")
    public Result<Object> microPay(@RequestParam("orders") String orders, @RequestParam("authCode") String authCode) {
        Result<Object> result = new Result<>();
        DeviceCarModel deviceCarModel = tangOrderService.getDeviceCarModel(orders);
        Addr addr = addrService.getOne(new QueryWrapper<Addr>().lambda().eq(Addr::getAddrNo, deviceCarModel.getAddr()));
        if (addr == null) {
            return Result.error(500, "地点表错误");
        }
        deviceCarModel.setAddrName(addr.getAddrName());
        int payChannel = 0;
        String codeType = authCode.substring(0, 2);


        if (Integer.parseInt(codeType) > 20) {
            payChannel = 1;
            return Result.error("二维码错误,请重新扫码");
        }

        TangOrder tangOrder = tangOrderService.getOne(new QueryWrapper<TangOrder>().lambda().eq(TangOrder::getOrders, orders));

        try {
            deviceCarModel.setPayChannelName("微信支付");
            WXEntity wxEntity = new WXEntity();
            WXPay wxPay = new WXPay(wxEntity);
            //start pay
            Map<String, String> reqMap = new HashMap<>();
            reqMap.put("body", "tangshi");
            reqMap.put("out_trade_no", tangOrder.getOrders());
            reqMap.put("spbill_create_ip", "8.8.8.8");
            reqMap.put("total_fee", new BigDecimal(tangOrder.getAmountPrice()).multiply(new BigDecimal(100)).stripTrailingZeros().toPlainString());
            reqMap.put("auth_code", authCode);
            reqMap.put("sub_mch_id", addr.getSubMchId());
            Map<String, String> resMap = wxPay.microPay(reqMap);
            log.info(resMap.toString());
            if (!"SUCCESS".equals(resMap.get("result_code")) || !"SUCCESS".equals(resMap.get("return_code"))) {
                log.info("支付系统错误，需要进行查单");
                deviceCarModel.setResultCode(-1);
            }
            result.setResult(JSONObject.toJSONString(deviceCarModel));
        } catch (Exception e) {
            e.printStackTrace();
        }
        tangOrderService.updateTangOrderPayChannel(tangOrder.getId(), 1);
        return result;
    }

    @GetMapping("microPayBatch")
    public Result<Object> microPayBatch(@RequestParam("orders") String orders, @RequestParam("authCode") String authCode) {
        Result<Object> result = new Result<>();
        List<DeviceCarModel> deviceCarModel = tangOrderService.getDeviceCarModelForList(orders);
        List<Addr> addrList = addrService.list();
        String addrSub = "";
        for (DeviceCarModel goo : deviceCarModel) {
            Addr addr = addrList.stream().filter(u -> u.getAddrNo() == goo.getAddr()).findFirst().orElse(null);
            goo.setAddrName(addr == null ? "" : addr.getAddrName());
            goo.setPayChannelName("微信支付");
            if (addr == null || addr.getSubMchId() == null) {
                return Result.error("商铺Addr设置有误，请联系管理员");
            }
            if ("".equals(addrSub)) {
                addrSub = addr.getSubMchId();
            } else if (!addrSub.equals(addr.getSubMchId())) {
                return Result.error("所选择的商户支付Sub_mch出现冲突，请联系管理员");
            }
        }
        int payChannel = 0;
        String codeType = authCode.substring(0, 2);
        if (Integer.parseInt(codeType) > 20) {
            payChannel = 1;
            return Result.error("二维码错误,请重新扫码");
        }
        List<TangOrder> tangOrderList = tangOrderService.list(new QueryWrapper<TangOrder>().lambda().eq(TangOrder::getOrders, orders));

        BigDecimal priceBig = new BigDecimal(0);
        for (TangOrder goo : tangOrderList) {
            priceBig = priceBig.add(new BigDecimal(goo.getAmountPrice()));
        }
        try {

            WXEntity wxEntity = new WXEntity();
            WXPay wxPay = new WXPay(wxEntity);
            //start pay
            Map<String, String> reqMap = new HashMap<>();
            reqMap.put("body", "tangshi");
            reqMap.put("out_trade_no", orders);
            reqMap.put("spbill_create_ip", "8.8.8.8");
            reqMap.put("total_fee", priceBig.multiply(new BigDecimal(100)).stripTrailingZeros().toPlainString());
            reqMap.put("auth_code", authCode);
            reqMap.put("sub_mch_id", addrSub);
            Map<String, String> resMap = wxPay.microPay(reqMap);
            log.info(resMap.toString());
            if (!"SUCCESS".equals(resMap.get("result_code")) || !"SUCCESS".equals(resMap.get("return_code"))) {
                log.info("支付系统错误，需要进行查单");
                for (DeviceCarModel goo : deviceCarModel) {
                    goo.setResultCode(-1);
                }
            } else {
                for (DeviceCarModel carModel : deviceCarModel) {
                    depotCardBatch(carModel, orders);
                }
            }
            result.setResult(JSONArray.toJSONString(deviceCarModel));
        } catch (Exception e) {
            e.printStackTrace();
        }
        tangOrderService.updateTangOrderPayChannelByOrders(orders, 1);
        return result;
    }

    private void depotCardBatch(DeviceCarModel deviceCarModel, String orders) {
        BigDecimal amountCount = new BigDecimal(0);
        BigDecimal amountPrice = new BigDecimal(0);
        for (CarFoodsModel goo : deviceCarModel.getCarFoods()) {
            amountCount = amountCount.add(new BigDecimal(goo.getFoodNumber()));
            amountPrice = amountPrice.add(new BigDecimal(goo.getFoodNumber()).multiply(new BigDecimal(goo.getPrice())));
        }
        deviceCarModel.setAmountPrice(amountPrice);
        deviceCarModel.setAmountCount(amountCount);
        TangDevice tangDevice = tangDeviceService.getOne(new QueryWrapper<TangDevice>().lambda()
                .eq(TangDevice::getPosnum, deviceCarModel.getOperaId()));
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<InStockTempVo> inStockTempVoList = new ArrayList<>();
        for (CarFoodsModel goo : deviceCarModel.getCarFoods()) {
            Device device = deviceService.getOne(new QueryWrapper<Device>().lambda()
                    .eq(Device::getDeviceid, goo.getBm()));
            InStockTempVo inStockTempVo = new InStockTempVo();
            inStockTempVo.setDeviceid(goo.getBm());
            inStockTempVo.setDevicename(device.getDevicename());
            inStockTempVo.setLogid(deviceCarModel.getOperaId());
            inStockTempVo.setUnit(device.getUnit());
            inStockTempVo.setFlag("CH");
            inStockTempVo.setNumber(inStockTempVo.getNumber());
            inStockTempVo.setLastnumber(ObjectUtil.getBigDecimal(goo.getMaxNumber()));
            inStockTempVo.setPriceVer(goo.getPriceVer());
            inStockTempVo.setPrice(device.getPrice().floatValue());
            inStockTempVo.setSalePrice(new BigDecimal(goo.getPrice()).floatValue());
            inStockTempVo.setNumber(new BigDecimal(goo.getFoodNumber()));
            inStockTempVo.setDh(orders);
            inStockTempVo.setAddr(tangDevice.getAddr());
            inStockTempVo.setCkId(tangDevice.getCkId());
            inStockTempVo.setPihao(orders);
            inStockTempVo.setXddate(simpleDateFormat.format(new Date()));
            inStockTempVo.setCardno(tangDevice.getCardno());
            inStockTempVo.setSc("3");
            inStockTempVo.setInDate(new Date());
            inStockTempVo.setPid(goo.getPid());

            inStockTempVo.setProvider(goo.getProvider());
            inStockTempVo.setPriceAdjustTimes(goo.getPriceAdjustTimes());
            InStockTempVo inStockTempVoTemp = new InStockTempVo();
            BeanUtils.copyProperties(inStockTempVo, inStockTempVoTemp);
            inStockTempVoList.add(inStockTempVoTemp);
        }
        Fk fk = fkService.getOne(new QueryWrapper<Fk>().eq("cardNo", tangDevice.getCardno()));
        if(fk == null) {
            fk = new Fk();
            fk.setCardno(tangDevice.getCardno());
            fk.setKl("");
        }
        inStockService.insertInStock(inStockTempVoList, tangDevice);
        reserveService.depotCardPay(tangDevice, inStockTempVoList, fk, orders, "3", null);
    }

    @PostMapping("facePay")
    public Result<Object> facePay(@RequestBody JSONObject reqJson) {
        Result<Object> result = new Result<>();
        String faceToken = reqJson.getString("faceToken");
        String orders = reqJson.getString("orders");
        String aliUid = reqJson.getString("aliUid");
        String terminalParams = reqJson.getString("terminal_params");
        List<DeviceCarModel> deviceCarModel = tangOrderService.getDeviceCarModelForList(orders);
        List<Addr> addrList = addrService.list();
        String appAuthToken = "";
        for (DeviceCarModel goo : deviceCarModel) {
            Addr addr = addrList.stream().filter(u -> u.getAddrNo() == goo.getAddr()).findFirst().orElse(null);
            goo.setAddrName(addr == null ? "" : addr.getAddrName());
            goo.setPayChannelName("支付宝刷脸支付");
            if (addr == null || addr.getAliAppAuthToken() == null) {
                return Result.error("商铺Addr设置有误，请联系管理员");
            }
            appAuthToken = addr.getAliAppAuthToken();
        }
        List<TangOrder> tangOrderList = tangOrderService.list(new QueryWrapper<TangOrder>().lambda().eq(TangOrder::getOrders, orders));
        BigDecimal priceBig = new BigDecimal(0);
        for (TangOrder goo : tangOrderList) {
            priceBig = priceBig.add(new BigDecimal(goo.getAmountPrice()));
        }
        try {
            AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do",
                    AliPayUtil.getAppid(), AliPayUtil.getPrivateKey(), "json", "GBK",
                    AliPayUtil.getPublicKey(), "RSA2");
            AlipayTradePayRequest request = new AlipayTradePayRequest();
            JsonsRootBean jsonsRootBean = new JsonsRootBean(orders, priceBig.toPlainString(), faceToken, terminalParams, "");
            request.setBizContent(JSONObject.toJSONString(jsonsRootBean));
            AlipayTradePayResponse response = alipayClient.execute(request, null, appAuthToken);
            log.info(JSONObject.toJSONString(response));
            if (!response.isSuccess()) {
                log.error("支付失败,需要进行查单");
                for (DeviceCarModel goo : deviceCarModel) {
                    goo.setResultCode(-1);
                }
            }
            result.setResult(JSONArray.toJSONString(deviceCarModel));
        } catch (Exception e) {
            e.printStackTrace();
        }
        tangOrderService.updateTangOrderPayChannelByOrders(orders, 2);
        return result;
    }

    @GetMapping("checkAliOrderStatus")
    public Result<Object> checkAliOrderStatus(@RequestParam("orders") String orders) {
        Result<Object> result = new Result<>();
        List<DeviceCarModel> deviceCarModel = tangOrderService.getDeviceCarModelForList(orders);
        List<Addr> addrList = addrService.list();
        String appAuthToken = "";
        for (DeviceCarModel goo : deviceCarModel) {
            Addr addr = addrList.stream().filter(u -> u.getAddrNo() == goo.getAddr()).findFirst().orElse(null);
            goo.setAddrName(addr == null ? "" : addr.getAddrName());
            goo.setPayChannelName("支付宝刷脸支付");
            if (addr == null || addr.getSubMchId() == null) {
                return Result.error("商铺Addr设置有误，请联系管理员");
            }
            goo.setResultCode(-1);
            appAuthToken = addr.getAliAppAuthToken();
        }
        try {
            AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do",
                    AliPayUtil.getAppid(), AliPayUtil.getPrivateKey(), "json", "GBK",
                    AliPayUtil.getPublicKey(), "RSA2");
            AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
            AlipayTradeQueryModel model = new AlipayTradeQueryModel();
            model.setOutTradeNo(orders);
            JSONObject bizContent = new JSONObject();
            bizContent.put("out_trade_no", orders);
            request.setBizContent(bizContent.toString());
            AlipayTradeQueryResponse response = alipayClient.execute(request,null, appAuthToken);
            log.info(JSONObject.toJSONString(response));
            if (response.isSuccess()) {
                for (DeviceCarModel goo : deviceCarModel) {
                    goo.setResultCode(1);
                }
            }
            result.setResult(JSONArray.toJSONString(deviceCarModel));
        } catch (Exception e) {
            e.printStackTrace();
        }
        tangOrderService.updateTangOrderPayStateByOrders(orders, 0);
        return result;
    }

    @GetMapping("checkOrder")
    public Result<Object> checkOrder(@RequestParam("orders") String orders) {
        Result<Object> result = new Result<>();
        DeviceCarModel deviceCarModel = tangOrderService.getDeviceCarModel(orders);
        Addr addr = addrService.getOne(new QueryWrapper<Addr>().lambda().eq(Addr::getAddrNo, deviceCarModel.getAddr()));
        deviceCarModel.setAddrName(addr.getAddrName());
        try {
            deviceCarModel.setPayChannelName("微信支付");
            WXEntity wxEntity = new WXEntity();
            WXPay wxPay = new WXPay(wxEntity);
            //start pay
            Map<String, String> reqMap = new HashMap<>();
            reqMap.put("out_trade_no", orders);
            reqMap.put("sub_mch_id", addr.getSubMchId());
            Map<String, String> resMap = wxPay.orderQuery(reqMap);
            System.out.println(resMap.toString());
            log.info(resMap.toString());
            if (!"SUCCESS".equals(resMap.get("return_code")) && !"SUCCESS".equals(resMap.get("return_code"))) {
                log.info("支付系统错误，需要进行查单");
                deviceCarModel.setResultCode(-1);
            } else if ("SUCCESS".equals(resMap.get("trade_state")) || "ACCEPT".equals(resMap.get("trade_state"))) {
                //支付成功订单
                deviceCarModel.setResultCode(1);
                depotCardBatch(deviceCarModel, orders);
            } else if ("USERPAYING".equals(resMap.get("trade_state"))) {
                deviceCarModel.setResultCode(0);
            } else {
                deviceCarModel.setResultCode(-1);
            }
            result.setResult(JSONObject.toJSONString(deviceCarModel));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    @GetMapping("checkOrderBatch")
    public Result<Object> checkOrderBatch(@RequestParam("orders") String orders) {
        Result<Object> result = new Result<>();
        List<DeviceCarModel> deviceCarModel = tangOrderService.getDeviceCarModelForList(orders);
        List<Addr> addrList = addrService.list();
        String addrSub = "";
        for (DeviceCarModel goo : deviceCarModel) {
            Addr addr = addrList.stream().filter(u -> u.getAddrNo() == goo.getAddr()).findFirst().orElse(null);
            goo.setAddrName(addr == null ? "" : addr.getAddrName());
            goo.setPayChannelName("微信支付");
            if (addr == null || addr.getSubMchId() == null) {
                return Result.error("商铺Addr设置有误，请联系管理员");
            }
            if ("".equals(addrSub)) {
                addrSub = addr.getSubMchId();
            } else if (!addrSub.equals(addr.getSubMchId())) {
                return Result.error("所选择的商户支付Sub_mch出现冲突，请联系管理员");
            }
        }
        try {
            WXEntity wxEntity = new WXEntity();
            WXPay wxPay = new WXPay(wxEntity);
            //start pay
            Map<String, String> reqMap = new HashMap<>();
            reqMap.put("out_trade_no", orders);
            reqMap.put("sub_mch_id", addrSub);
            Map<String, String> resMap = wxPay.orderQuery(reqMap);
            System.out.println(resMap.toString());
            log.info(resMap.toString());
            if (!"SUCCESS".equals(resMap.get("return_code")) && !"SUCCESS".equals(resMap.get("return_code"))) {
                log.info("支付系统错误，需要进行查单");
//                deviceCarModel.setResultCode(-1);
                for (DeviceCarModel goo : deviceCarModel) {
                    goo.setResultCode(-1);
                }
            } else if ("SUCCESS".equals(resMap.get("trade_state")) || "ACCEPT".equals(resMap.get("trade_state"))) {
                //支付成功订单
//                deviceCarModel.setResultCode(1);
                for (DeviceCarModel goo : deviceCarModel) {
                    goo.setResultCode(1);
                }
            } else if ("USERPAYING".equals(resMap.get("trade_state"))) {
//                deviceCarModel.setResultCode(0);
                for (DeviceCarModel goo : deviceCarModel) {
                    goo.setResultCode(0);
                }
            } else {
//                deviceCarModel.setResultCode(-1);
                for (DeviceCarModel goo : deviceCarModel) {
                    goo.setResultCode(-1);
                }
            }
            result.setResult(JSONObject.toJSONString(deviceCarModel));
        } catch (Exception e) {
            e.printStackTrace();
        }
        tangOrderService.updateTangOrderPayStateByOrders(orders, 0);
        return result;
    }


    /**
     * 现金支付
     *
     * @return
     */
    @PostMapping("cashPay")
    public Result<Object> cashPay(@RequestBody DeviceCarModel deviceCarModel) {
        Result<Object> result = new Result<>();
        String date = new SimpleDateFormat("MMdd").format(new Date());
        String orders = "XJZF" + date + SnowFlake.nextId();
        cashBatch(deviceCarModel, orders);
//        String liushui = tangOrderService.getLiuShui();
//        sumJe(deviceCarModel);//计算价格
//        Addr addr = addrService.getOne(new QueryWrapper<Addr>().lambda().eq(Addr::getAddrNo, deviceCarModel.getAddr()));
//        deviceCarModel.setAddrName(addr.getAddrName());
//        deviceCarModel.setOrders(orders);
//        deviceCarModel.setPayChannelName("现金支付");
//        deviceCarModel.setLiushui(liushui);
//        TangOrder tangOrder = new TangOrder();
//        tangOrder.setOrders(orders);
//        tangOrder.setOperaId(deviceCarModel.getOperaId());
//        tangOrder.setPosNum(deviceCarModel.getPosNum());
//        tangOrder.setPayChannel(3);
//        tangOrder.setPayState(1);
//        tangOrder.setNoticeReserve(0);
//        tangOrder.setAddr(deviceCarModel.getAddr());
//        tangOrder.setAmountCount(deviceCarModel.getAmountCount().intValue());
//        tangOrder.setAmountPrice(deviceCarModel.getAmountPrice().toPlainString());
//        tangOrder.setQcCode(liushui);
//        tangOrder.setCreateTime(new Date());
//        tangOrderService.save(tangOrder);
//        List<TangOrderDetails> tangOrderDetailsList = new ArrayList<>();
//        for (CarFoodsModel goo : deviceCarModel.getCarFoods()) {
//            TangOrderDetails tangOrderDetails = new TangOrderDetails();
//            tangOrderDetails.setOrdersId(tangOrder.getId());
//            tangOrderDetails.setBmzl(goo.getZl());
//            tangOrderDetails.setNumber(goo.getFoodNumber());
//            tangOrderDetails.setCode(goo.getBm());
//            tangOrderDetails.setFoodName(goo.getName());
//            tangOrderDetails.setPrice(goo.getPrice());
//            tangOrderDetails.setAmountPrice(new BigDecimal(goo.getPrice()).multiply(new BigDecimal(goo.getFoodNumber())).toPlainString());
//            tangOrderDetailsList.add(tangOrderDetails);
//        }
//        tangOrderDetailsService.saveBatch(tangOrderDetailsList);
        result.setResult(JSONObject.toJSONString(deviceCarModel));
        return result;
    }


    @PostMapping("cashPayBatch")
    public Result<Object> cashPayBatch(@RequestBody List<DeviceCarModel> deviceCarModelList) {
        Result<Object> result = new Result<>();
        System.out.println(deviceCarModelList.toString());
        List<DeviceCarModel> resDeviceCarModelList = new ArrayList<>();
        String date = new SimpleDateFormat("MMdd").format(new Date());
        String orders = "XJZF" + date + SnowFlake.nextId();
        for (DeviceCarModel goo : deviceCarModelList) {
            DeviceCarModel deviceCarModel = cashBatch(goo, orders);
            resDeviceCarModelList.add(deviceCarModel);
        }
        result.setResult(JSONArray.toJSONString(deviceCarModelList));
//        result.setResult(JSONObject.toJSONString(deviceCarModel));
        return result;
    }

    @PostMapping("depotCashPayBatch")
    public Result<Object> depotCashPayBatch(@RequestBody List<DeviceCarModel> deviceCarModelList) {
        Result<Object> result = new Result<>();
        List<DeviceCarModel> resDeviceCarModelList = new ArrayList<>();
        String date = new SimpleDateFormat("MMdd").format(new Date());
        String orders = "XJZF" + date + SnowFlake.nextId();
        for (DeviceCarModel goo : deviceCarModelList) {
            DeviceCarModel deviceCarModel = depotCashBatch(goo, orders);
            resDeviceCarModelList.add(deviceCarModel);
        }
        result.setResult(JSONArray.toJSONString(deviceCarModelList));
        return result;
    }

    //一条出库记录，一条RESERVE记录
    private DeviceCarModel depotCashBatch(DeviceCarModel deviceCarModel, String orders) {
        String liushui = tangOrderService.getLiuShui();
        sumJe(deviceCarModel);//计算价格
//        String order = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + liushui;
        TangDevice tangDevice = tangDeviceService.getOne(new QueryWrapper<TangDevice>().lambda().eq(TangDevice::getPosnum, deviceCarModel.getPosNum()));

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (CarFoodsModel goo : deviceCarModel.getCarFoods()) {
            Device device = deviceService.getOne(new QueryWrapper<Device>().lambda().eq(Device::getDeviceid, goo.getBm()));
            InventoryNumberDto dto = new InventoryNumberDto(tangDevice.getAddr(), tangDevice.getCkId(), goo.getBm());
            Map<String, Object> inventoryMap = inStockService.queryInventoryByDeviceId(dto);
            BigDecimal lastNumber = inventoryMap != null ? ObjectUtil.getBigDecimal(inventoryMap.get("number")) : new BigDecimal(0);
            InStockTempVo inStockTempVo = new InStockTempVo();
            inStockTempVo.setDeviceid(goo.getBm());
            inStockTempVo.setDevicename(device.getDevicename());
            inStockTempVo.setLogid(deviceCarModel.getOperaId());
            inStockTempVo.setFlag("CH");
            inStockTempVo.setNumber(inStockTempVo.getNumber());
            inStockTempVo.setLastnumber(lastNumber);
            inStockTempVo.setPriceVer(goo.getPriceVer());
            inStockTempVo.setPrice(device.getPrice().floatValue());
            inStockTempVo.setSalePrice(new BigDecimal(goo.getPrice()).floatValue());
            inStockTempVo.setNumber(new BigDecimal(goo.getFoodNumber()));
            inStockTempVo.setDh(orders);
            inStockTempVo.setAddr(tangDevice.getAddr());
            inStockTempVo.setCkId(tangDevice.getCkId());
            inStockTempVo.setPihao(orders);
            inStockTempVo.setXddate(simpleDateFormat.format(new Date()));
            inStockTempVo.setCardno(tangDevice.getCardno());
            inStockTempVo.setSc("2");
            singleOutFromDB(inStockTempVo);
        }
        return null;
    }

    public InStockTempVo singleOutFromDB(InStockTempVo inStockTempVo) {
        //记录原来入库数量，同时记录转后后数量，单位转换后要返回原数量给前端
        Result<InStockTempVo> result = new Result<>();
        inStockTempVo.setInDate(new Date());
        inStockTempVo.setPid(0);
        inStockTempVo.setProvider("(小卖部)");
        InStockTempVo inStockTempVoTemp = new InStockTempVo();
        BeanUtils.copyProperties(inStockTempVo, inStockTempVoTemp);
        Long returnId = inStockService.saveInStock(inStockTempVoTemp);
        if (returnId > 0) {
            inStockTempVo.setId(returnId);
            inStockTempVoTemp.setId(returnId);
            result.setResult(inStockTempVoTemp);
            return inStockTempVoTemp;
        }
        return null;
    }


    private DeviceCarModel cashBatch(DeviceCarModel deviceCarModel, String orders) {
        String liushui = tangOrderService.getLiuShui();
        sumJe(deviceCarModel);//计算价格
        Addr addr = addrService.getOne(new QueryWrapper<Addr>().lambda().eq(Addr::getAddrNo, deviceCarModel.getAddr()));
        deviceCarModel.setAddrName(addr.getAddrName());
        deviceCarModel.setOrders(orders);
        deviceCarModel.setPayChannelName("现金支付");
        deviceCarModel.setLiushui(liushui);
        TangOrder tangOrder = new TangOrder();
        tangOrder.setOrders(orders);
        tangOrder.setOperaId(deviceCarModel.getOperaId());
        tangOrder.setPosNum(deviceCarModel.getPosNum());
        tangOrder.setPayChannel(3);
        tangOrder.setPayState(1);
        tangOrder.setNoticeReserve(0);
        tangOrder.setAddr(deviceCarModel.getAddr());
        tangOrder.setAmountCount(deviceCarModel.getAmountCount().intValue());
        tangOrder.setAmountPrice(deviceCarModel.getAmountPrice().toPlainString());
        tangOrder.setQcCode(liushui);
        tangOrder.setCreateTime(new Date());
        tangOrderService.save(tangOrder);
        List<TangOrderDetails> tangOrderDetailsList = new ArrayList<>();
        for (CarFoodsModel goo : deviceCarModel.getCarFoods()) {
            TangOrderDetails tangOrderDetails = new TangOrderDetails();
            tangOrderDetails.setOrdersId(tangOrder.getId());
            tangOrderDetails.setBmzl(goo.getZl());
            tangOrderDetails.setNumber(goo.getFoodNumber());
            tangOrderDetails.setCode(goo.getBm());
            tangOrderDetails.setFoodName(goo.getName());
            tangOrderDetails.setPrice(goo.getPrice());
            tangOrderDetails.setAmountPrice(new BigDecimal(goo.getPrice()).multiply(new BigDecimal(goo.getFoodNumber())).toPlainString());
            tangOrderDetailsList.add(tangOrderDetails);
        }
        tangOrderDetailsService.saveBatch(tangOrderDetailsList);
        return deviceCarModel;
    }


    private void sumJe(DeviceCarModel deviceCarModel) {
        BigDecimal amountCount = new BigDecimal(0);
        BigDecimal amountPrice = new BigDecimal(0);
        for (CarFoodsModel goo : deviceCarModel.getCarFoods()) {
            amountCount = amountCount.add(new BigDecimal(goo.getFoodNumber()));
            amountPrice = amountPrice.add(new BigDecimal(goo.getFoodNumber()).multiply(new BigDecimal(goo.getPrice())));
        }
        deviceCarModel.setAmountPrice(amountPrice);
        deviceCarModel.setAmountCount(amountCount);
    }


    /**
     * 付款码支付，区分支付宝或者微信支付，同时写入日志表中，
     * 上传金额、机号
     * 返回订单号
     */
    @PostMapping("createOrders")
    @Transactional
    public Result<String> createOrders(@RequestBody JSONObject jsonObject) {
        String price = jsonObject.getString("price");
        String posnum = jsonObject.getString("posnum");
        int addr = jsonObject.getInteger("addr");
        String orders = SnowFlake.nextId() + "";
        TangOrder tangOrder = new TangOrder();
        tangOrder.setOrders(orders);
        tangOrder.setOperaId(posnum);
        tangOrder.setPosNum(posnum);
        tangOrder.setPayChannel(0);
        tangOrder.setPayState(0);
        tangOrder.setNoticeReserve(0);
        tangOrder.setAddr(addr);
        tangOrder.setAmountCount(1);
        tangOrder.setAmountPrice(price);
        tangOrder.setQcCode("");
        tangOrder.setCreateTime(new Date());
        tangOrderService.save(tangOrder);

        TangOrderDetails tangOrderDetails = new TangOrderDetails();
        tangOrderDetails.setOrdersId(tangOrder.getId());
        tangOrderDetails.setBmzl("9");
        tangOrderDetails.setNumber(1);
        tangOrderDetails.setCode("0000");
        tangOrderDetails.setFoodName("现金菜");
        tangOrderDetails.setPrice(price);
        tangOrderDetails.setAmountPrice(price);
        tangOrderDetailsService.save(tangOrderDetails);
        Result<String> result = new Result<>();
        result.setResult(orders);
        return result;
    }

    @PostMapping("toQRPay")
    public Result<PayResVo> toQRPay(@RequestBody JSONObject jsonObject) {
        Result<PayResVo> result = new Result<>();
        String authCode = jsonObject.getString("authCode");//二维码
        String orders = jsonObject.getString("orders");//单号
        String type = authCode.substring(0, 1);
        if ("1".equals(type)) {
            //微信支付
            PayResVo payResVo = weixnPayImpl(orders, authCode);
            result.setResult(payResVo);
            return result;
        } else if ("2".equals(type)) {
            //支付宝支付
            System.out.println("支付宝支付");
            PayResVo payResVo = aliPayImpl(orders, authCode);
            result.setResult(payResVo);
            return result;
        }
        PayResVo payResVo = new PayResVo();
        payResVo.setState(-1);
        payResVo.setMessage("找不到支付方式");
        result.setResult(payResVo);
        return result;
    }


    @PostMapping("checkOrders")
    public Result<PayResVo> checkOrders(@RequestBody JSONObject jsonObject) {
        Result<PayResVo> result = new Result<>();
        PayResVo payResVo = new PayResVo();
        String orders = jsonObject.getString("orders");
        //判断订单属于微信还是支付宝
        TangOrder tangOrder = tangOrderService.getOne(new QueryWrapper<TangOrder>().lambda().eq(TangOrder::getOrders, orders));
        if (tangOrder == null) {
            payResVo.setState(-1);
            payResVo.setMessage("订单号不存在");
            return result;
        }
        switch (tangOrder.getPayChannel()) {
            case 1:
                payResVo = weixinCheckImpl(orders);
                break;
            case 3:
                payResVo = aliCheckImpl(orders);
                break;
            default:
                payResVo.setMessage("订单状态有误，请核对");
                payResVo.setState(-1);
                break;
        }
        result.setResult(payResVo);
        return result;
    }

    private PayResVo aliPayImpl(String orders, String authCode) {
        PayResVo payResVo = new PayResVo();
        TangOrder tangOrder = tangOrderService.getOne(new QueryWrapper<TangOrder>().lambda().eq(TangOrder::getOrders, orders));
        if (tangOrder == null) {
            //返回错误
            payResVo.setState(-1);
            payResVo.setMessage("订单号不存在");
            return payResVo;
        }
        try {
            AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", AliPayUtil.getAppid(), AliPayUtil.getPrivateKey(), "json", "GBK", AliPayUtil.getPublicKey(), "RSA2");
            AlipayTradePayRequest request = new AlipayTradePayRequest();
            JSONObject bizContent = new JSONObject();
            bizContent.put("out_trade_no", orders);
            bizContent.put("total_amount", tangOrder.getAmountPrice());
            bizContent.put("subject", "现金菜");
            bizContent.put("scene", "bar_code");
            bizContent.put("auth_code", authCode);
            System.out.println(bizContent.toString());
//// 商品明细信息
//JSONArray goodsDetail = new JSONArray();
//JSONObject goods1 = new JSONObject();
//goods1.put("goods_id", "goodsNo1");
//goods1.put("goods_name", "子商品1");
//goods1.put("quantity", 1);
//goods1.put("price", 0.01);
//goodsDetail.add(goods1);
//bizContent.put("goods_detail", goodsDetail);

//// 扩展信息
//JSONObject extendParams = new JSONObject();
//extendParams.put("sys_service_provider_id", "2088511833207846");
//bizContent.put("extend_params", extendParams);

//// 结算信息
//JSONObject settleInfo = new JSONObject();
//JSONArray settleDetailInfos = new JSONArray();
//JSONObject settleDetail = new JSONObject();
//settleDetail.put("trans_in_type", "defaultSettle");
//settleDetail.put("amount", 0.01);
//settleDetailInfos.add(settleDetail);
//settleInfo.put("settle_detail_infos", settleDetailInfos);
//bizContent.put("settle_info", settleInfo);

//// 二级商户信息
//JSONObject subMerchant = new JSONObject();
//subMerchant.put("merchant_id", "2088000603999128");
//bizContent.put("sub_merchant", subMerchant);

//// 业务参数信息
//JSONObject businessParams = new JSONObject();
//businessParams.put("busi_params_key", "busiParamsValue");
//bizContent.put("business_params", businessParams);

//// 营销信息
//JSONObject promoParams = new JSONObject();
//promoParams.put("promo_params_key", "promoParamsValue");
//bizContent.put("promo_params", promoParams);

//// 返回参数选项
//JSONArray queryOptions = new JSONArray();
//queryOptions.add("fund_bill_list");
//queryOptions.add("voucher_detail_list");
//bizContent.put("query_options", queryOptions);
            request.setBizContent(bizContent.toString());
            AlipayTradePayResponse response = alipayClient.execute(request, null, AliPayUtil.getAppAuthToken());
            if (response.isSuccess()) {
                System.out.println("调用成功");
                payResVo.setState(0);
                payResVo.setMessage("调用失败");
            } else {
                payResVo.setState(-1);
                payResVo.setMessage("调用失败");
                System.out.println("调用失败");
            }
        } catch (Exception e) {
            payResVo.setState(-1);
            payResVo.setMessage(e.getMessage());
            return payResVo;
        }
        tangOrderService.updateTangOrderPayChannel(tangOrder.getId(), 3);
        return payResVo;
    }

    private PayResVo weixnPayImpl(String orders, String authCode) {
        PayResVo payResVo = new PayResVo();
        payResVo.setState(1);
        payResVo.setMessage("支付成功");
        //查询订单号，是否为空
        TangOrder tangOrder = tangOrderService.getOne(new QueryWrapper<TangOrder>().lambda().eq(TangOrder::getOrders, orders));
        if (tangOrder == null) {
            //返回错误
            payResVo.setState(-1);
            payResVo.setMessage("订单号不存在");
            return payResVo;
        }
        try {
            WXEntity wxEntity = new WXEntity();
            WXPay wxPay = new WXPay(wxEntity);
            //start pay
            Map<String, String> reqMap = new HashMap<>();
            reqMap.put("body", "手持机现金菜");
            reqMap.put("out_trade_no", tangOrder.getOrders());
            reqMap.put("spbill_create_ip", "8.8.8.8");
            reqMap.put("total_fee", new BigDecimal(tangOrder.getAmountPrice())
                    .multiply(new BigDecimal(100)).stripTrailingZeros().toPlainString());
            reqMap.put("auth_code", authCode);
            reqMap.put("sub_mch_id", WXPayUtils.getSubMchId());
            Map<String, String> resMap = wxPay.microPay(reqMap);
            log.info(resMap.toString());
            if (!"SUCCESS".equals(resMap.get("result_code")) || !"SUCCESS".equals(resMap.get("return_code"))) {
                log.info("支付系统错误，需要进行查单");
                payResVo.setState(0);
                payResVo.setMessage("重新查单");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        tangOrderService.updateTangOrderPayChannel(tangOrder.getId(), 1);
        return payResVo;
    }

    private PayResVo weixinCheckImpl(String orders) {
        PayResVo payResVo = new PayResVo();
        try {
            WXEntity wxEntity = new WXEntity();
            WXPay wxPay = new WXPay(wxEntity);
            Map<String, String> reqMap = new HashMap<>();
            reqMap.put("out_trade_no", orders);
            reqMap.put("sub_mch_id", WXPayUtils.getSubMchId());
            Map<String, String> resMap = wxPay.orderQuery(reqMap);
            System.out.println(resMap.toString());
            log.info(resMap.toString());
            if (!"SUCCESS".equals(resMap.get("return_code")) && !"SUCCESS".equals(resMap.get("return_code"))) {
                log.info("支付系统错误，需要进行查单");
                payResVo.setState(0);
                payResVo.setMessage("支付系统错误，需要查单");
            } else if ("SUCCESS".equals(resMap.get("trade_state")) || "ACCEPT".equals(resMap.get("trade_state"))) {
                //支付成功订单
                payResVo.setState(1);
                payResVo.setMessage("支付成功");
            } else if ("USERPAYING".equals(resMap.get("trade_state"))) {
                payResVo.setState(0);
                payResVo.setMessage("等待用户输入密码");
            } else {
                payResVo.setState(-1);
                payResVo.setMessage("交易失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return payResVo;
    }

    private PayResVo aliCheckImpl(String orders) {
        PayResVo payResVo = new PayResVo();
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do",
                AliPayUtil.getAppid(), AliPayUtil.getPrivateKey(), "json", "GBK", AliPayUtil.getPublicKey(), "RSA2");
        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("out_trade_no", orders);
        request.setBizContent(jsonObject.toJSONString());
        try {
            AlipayTradeQueryResponse response = alipayClient.execute(request, null, AliPayUtil.getAppAuthToken());
            if (response.isSuccess()) {
                System.out.println("调用成功");
                if ("WAIT_BUYER_PAY".equals(response.getTradeStatus())) {
                    payResVo.setState(0);
                    payResVo.setMessage("等待用户支付");
                } else if ("TRADE_SUCCESS".equals(response.getTradeStatus())) {
                    payResVo.setState(1);
                    payResVo.setMessage("支付成功");
                } else {
                    payResVo.setState(-1);
                    payResVo.setMessage("支付失败");
                }
            } else {
                System.out.println("调用失败");
            }
        } catch (Exception e) {
            payResVo.setState(-1);
            payResVo.setMessage("系统异常");
        }
        return payResVo;
    }


    @GetMapping("tk")
    public void tk(@RequestParam("orders") String orders,
                   @RequestParam("price") String price) throws Exception {
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do",
                AliPayUtil.getAppid(), AliPayUtil.getPrivateKey(), "json", "GBK", AliPayUtil.getPublicKey(), "RSA2");
        AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
        AlipayTradeRefundModel model = new AlipayTradeRefundModel();
        model.setRefundAmount(price);
        model.setOutTradeNo(orders);
        model.setOutRequestNo(String.valueOf(System.currentTimeMillis()));
        request.setBizModel(model);
        AlipayTradeRefundResponse response = alipayClient.execute(request, null, "202308BBd127680e0ea34391a01ac5700eddeF66");
        if (response.isSuccess()) {
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
        }
    }

    @GetMapping("corders")
    public void corders(@RequestParam("orders") String orders) throws Exception {
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do",
                AliPayUtil.getAppid(), AliPayUtil.getPrivateKey(), "json", "GBK", AliPayUtil.getPublicKey(), "RSA2");
//        AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
//        AlipayTradeRefundModel model = new AlipayTradeRefundModel();
        AlipayTradeQueryModel model = new AlipayTradeQueryModel();
        model.setOutTradeNo(orders);
//        model.setOutRequestNo(String.valueOf(System.currentTimeMillis()));
        request.setBizModel(model);
        AlipayTradeQueryResponse response = alipayClient.execute(request, null, AliPayUtil.getAppAuthToken());
        System.out.println(response.toString());
        if (response.isSuccess()) {
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
        }
    }

    @GetMapping("dz")
    public void dz() throws Exception {
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", AliPayUtil.getAppid(),
                AliPayUtil.getPrivateKey(), "json", "GBK", AliPayUtil.getPublicKey(), "RSA2");
        AlipayDataDataserviceBillDownloadurlQueryRequest request = new AlipayDataDataserviceBillDownloadurlQueryRequest();
        JSONObject json = new JSONObject();
        json.put("bill_type", "trade");
        json.put("bill_date", "2022-12-03");
        request.setBizContent(json.toString());
        AlipayDataDataserviceBillDownloadurlQueryResponse response = alipayClient.execute(request, null, AliPayUtil.getAppAuthToken());
        System.out.println(response.getBody());
        System.out.println(response.getBillDownloadUrl());
        if (response.isSuccess()) {
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
        }
    }

//    public static AlipayDataDataserviceBillDownloadurlQueryResponse clliet(String bill_date, String appId, String private_key, String public_key) {
//        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", appId, private_key,
//                "json", "GBK", public_key, "RSA"); //根据请求提示 有的是RSA2S
//        AlipayDataDataserviceBillDownloadurlQueryRequest request = new AlipayDataDataserviceBillDownloadurlQueryRequest();
//        JSONObject json = new JSONObject();
//        json.put("bill_type", "trade");
//        // 昨天的数据
//        json.put("bill_date", bill_date);
//        request.setBizContent(json.toString());
//        AlipayDataDataserviceBillDownloadurlQueryResponse response = null;
//        try {
//            response = alipayClient.execute(request);
//        } catch (AlipayApiException e) {
//            e.printStackTrace();
//        }
//        return response;
//    }

    @PostMapping("toDepotPrePayBatch")
    public Result<Object> toDepotPrePayBatch(@RequestBody JSONObject jsonObject) throws Exception {
        Result<Object> result = new Result<>();
        IPayRuleHandler ruleHandler = (IPayRuleHandler) Class
                .forName("com.gzdh.tang.warehouse.rule.WarehousePayRule")
                .newInstance();
        try {
            JSONObject resJson = ruleHandler.toCardPay(jsonObject);
            jsonObject.putAll(resJson);
        } catch (RuntimeException e) {
            e.printStackTrace();
            result.setCode(500);
            result.setMessage(e.getMessage());
        }
        result.setResult(jsonObject);
        return result;
    }

}
